package com.mall4j.cloud.user.controller.multishop;

import com.mall4j.cloud.common.response.ResponseEnum;
import com.mall4j.cloud.common.response.ServerResponseEntity;
import com.mall4j.cloud.user.dto.BalanceVo;
import com.mall4j.cloud.user.model.UserBalance;
import com.mall4j.cloud.user.service.UserBalanceService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;

@RestController("multishopUserBalanceController")
@Api(tags = "店铺-用户余额")
@RequestMapping("/m/userBalance")
public class UserBalanceController {

    @Autowired
    private  UserBalanceService userBalanceService;


    @PostMapping("/bind")
    @ApiOperation(value = "创建账户", notes = "传userId充值")
    public ServerResponseEntity<UserBalance> bindUserBalance(@RequestBody UserBalance userBalance) {
        UserBalance createdUserBalance = userBalanceService.createUserBalance(userBalance);
        return ServerResponseEntity.success(createdUserBalance);
    }

    //充值
    @PostMapping("/recharge")
    @ApiOperation(value = "充值", notes = "传userId充值")
    public ServerResponseEntity<String> recharge(@RequestBody BalanceVo balanceVo) {
        Long userId= balanceVo.getUserId();
        Double amount= balanceVo.getAmount();
        //先查账户创建没
        UserBalance userBalance= userBalanceService.getByUserId(userId);
        System.out.println(userBalance);
        if(userBalance==null){
            userBalance=new UserBalance();
            userBalance.setUserId(userId);
            userBalance.setBalance(BigDecimal.valueOf(amount));
            userBalanceService.createUserBalance(userBalance);
            return ServerResponseEntity.success("充值成功");
        }

        userBalance.setBalance(userBalance.getBalance().add(BigDecimal.valueOf(amount)));
        userBalanceService.update(userBalance);
        return ServerResponseEntity.success("充值成功");
    }

    @PostMapping("/withdraw")
    @ApiOperation(value = "提现", notes = "传userId提现")
    public ServerResponseEntity<String> withdraw(@RequestBody BalanceVo balanceVo) {

        UserBalance userBalance= userBalanceService.getByUserId(balanceVo.getUserId());
        if(userBalance.getBalance().compareTo(BigDecimal.valueOf(balanceVo.getAmount()))==-1){
            //钱不够
            return ServerResponseEntity.success("提现失败，余额不足");
        }
        userBalance.setBalance(userBalance.getBalance().subtract(BigDecimal.valueOf(balanceVo.getAmount())));
        userBalanceService.update(userBalance);
        return ServerResponseEntity.success("提现成功");
    }


    @GetMapping("/get")
    @ApiOperation(value = "查询", notes = "传userId查询余额")
    public ServerResponseEntity<UserBalance> withdraw(@RequestParam("userId") Long userId) {
        UserBalance userBalance= userBalanceService.getByUserId(userId);

        return ServerResponseEntity.success(userBalance);
    }
}
